package com.scalar.forecast.forecastEntry.actions;

import com.scalar.forecast.ForecastExtendedAction;
import com.scalar.forecast.commons.SessionKeys;
import com.scalar.forecast.forecastEntry.actionCommands.ForecastEntrySalesActionCommandFactory;
import com.scalar.forecast.forecastEntry.forms.ForecastEntryForm;
import com.scalar.forecast.forecastEntry.dao.ForecastEntryDAO;
import com.scalar.forecast.actionCommands.ActionCommand;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * User: Sujan Kumar
 * Date: Feb 14, 2005
 * Time: 12:50:38 PM
 */
public class ForecastEntrySalesAction extends ForecastExtendedAction
{
    public ActionForward executeRequest( ActionMapping mapping,
                                                      ActionForm form,
                                                      HttpServletRequest request,
                                                      HttpServletResponse response) throws Exception
    {
        ActionForward actionForward = mapping.findForward ( "forecastEntrySales" );
        String action = request.getParameter ( "action" );
        HashMap errors = new HashMap();
        HashMap info = new HashMap();
        HttpSession session = request.getSession();
        String salesPersonId = ( String ) session.getAttribute( USER_SALESPERSON_ID );
        if ( salesPersonId == null || salesPersonId.trim().length() == 0 )
        {
            errors.put ( "Only Sales Persons can enter Sales Forecast", null );
            request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
            return mapping.findForward ( "blankPage" );
        }
        else if ( !ForecastEntryDAO.isSlesPersonLevelValid( null, salesPersonId ) )
        {
            info.put ( INFO_SALESPERSON_LEVEL_NOT_MATCHED, "" );
            request.setAttribute ( INFO_MESSAGES, info );
            return mapping.findForward( "blankPage" );
        }
        try
        {
            if ( action == null )
            {
                action = ACTION_SEARCH;
            }
            ForecastEntryForm forecastEntryForm = ( ForecastEntryForm )form;
            forecastEntryForm.setBuild( false );
            ActionCommand actionCommand = ForecastEntrySalesActionCommandFactory.getActionCommand( action );
            if ( actionCommand != null)
            {
                actionForward = actionCommand.execute( mapping, form, request, response );
            }

        }
        catch( Exception e )
        {
            e.printStackTrace();
        }
        return actionForward;
    }
}
